<template>
  <!-- 弹出层 -->
  <van-popup v-model:show="data.show" position="bottom" round @close="confirmOn">
    <van-picker
      ref="picker"
      title="请选择时间"
      :columns="data.columns"
      @change="onChange"
      @cancel="cancelOn"
      @confirm="onConfirm"
      v-model="data.selectedValues"
    />
  </van-popup>
</template>
<script setup>
import { parseTime } from '@/utils/dlong';
import { reactive, watch, getCurrentInstance, computed } from 'vue';
import { compareDate } from '@/utils/util';

const customFieldName = {
  text: 'value',
  value: 'values',
  children: ''
};
const data = reactive({
  show: false, //是否显示弹出层
  columns: [], //所有时间列
  selectedValues: [] //控件选择的时间值
});

const props = defineProps({
  // 是否picker模式
  isPicker: {
    type: Boolean
  },
  // 传入的值
  values: {
    type: String,
    default: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
  },
  minDate: {
    type: [Date, String],
    default: ''
  },
  maxDate: {
    type: [Date, String],
    default: ''
  },
  seconds: {
    type: Boolean,
    default: false
  }
});

const min_date = computed(() => {
  return handleDate(props.minDate);
});

const max_date = computed(() => {
  return handleDate(props.maxDate);
});

//定义要向父组件传递的事件
const emit = defineEmits(['changeValue', 'confirm']);

watch(
  () => props.isPicker,
  val => {
    data.show = val;
    data.columns = [];
    getcolumns();
  },
  {
    immediate: true //立即监听--进入就会执行一次 监听显影状态
  }
);

function onChange(opts) {
  const { selectedValues } = opts;
  const [Y, M] = selectedValues;
  const change_date = handleConfirmDate(selectedValues);

  data.columns.splice(1, 1, setMonthColumn(change_date));
  data.columns.splice(2, 1, setDayColumn(Y, M, change_date));
  data.columns.splice(3, 1, setHourColumn(change_date));
  data.columns.splice(4, 1, setMinColumn(change_date));
  props.seconds && data.columns.splice(5, 1, setSecondsColumn(change_date));

  // 无用的方法
}

function handleDate(date) {
  if (!date) return '';
  let dateObj = new Date(Date.parse(date));
  return props.seconds
    ? parseTime(dateObj, '{y}-{m}-{d} {h}:{i}:{s}')
    : `${parseTime(dateObj, '{y}-{m}-{d} {h}:{i}')}:00`;
}

function getcolumns() {
  let strtime = props.values; //传入的时间
  //console.log(strtime); 2023-09-05 19:28:00
  let date = new Date(strtime.replace(/-/g, '/'));
  // console.log(date); Wed Aug 09 2023 14:53:15 GMT+0800 (中国标准时间)
  let timeVaules = date.getTime();

  let dateVaules;
  if (props.values != '') {
    dateVaules = new Date(timeVaules);
  } else {
    dateVaules = new Date(); //没有传入时间则默认当前时刻
  }

  let Y = dateVaules.getFullYear();
  let M = dateVaules.getMonth();
  let D = dateVaules.getDate();
  let h = dateVaules.getHours();
  let m = dateVaules.getMinutes();
  let s = dateVaules.getSeconds();

  // 个位数补0
  const _M = M < 10 ? `0${M + 1}` : (M + 1).toString(); //月份比实际获取的少1，所以要加1
  const _D = D < 10 ? `0${D}` : D.toString();
  const _h = h < 10 ? `0${h}` : h.toString();
  const _m = m < 10 ? `0${m}` : m.toString();
  const _s = s < 10 ? `0${s}` : s.toString();

  // 生成年月日时分秒时间值
  data.selectedValues.push(Y);
  data.selectedValues.push(_M);
  data.selectedValues.push(_D);
  data.selectedValues.push(_h);
  data.selectedValues.push(_m);
  data.selectedValues.push(_s);

  const cur_date = handleConfirmDate([Y, _M, _D, _h, _m, _s]);

  const year = setYearColumn(Y); //获取前后十年数组
  data.columns.push(year); //生成年列

  let month = setMonthColumn(cur_date); //获取12月数组
  data.columns.push(month); //生成月列

  //获取当月的天数
  const day = setDayColumn(Y, M + 1, cur_date);

  data.columns.push(day); //生成日列

  const hour = setHourColumn(cur_date); //创建小时数组
  data.columns.push(hour); //生成小时列

  const mi = setMinColumn(cur_date); //创建分钟数组
  data.columns.push(mi); //生成分钟列

  if (props.seconds) {
    const ss = setSecondsColumn(cur_date); //创建秒数数组
    data.columns.push(ss); //生成秒钟列
  }
}

function setDisabled(cur_date, type) {
  const min_res = min_date.value ? compareDate(cur_date, min_date.value, true) : false;
  const max_res = max_date.value ? compareDate(max_date.value, cur_date, true) : false;
  console.log(max_date.value, cur_date);
  type == 'm' && console.log(cur_date, min_date.value);
  return min_res || max_res;
}

function setYearColumn(Y) {
  let year = []; //获取前后十年数组
  year.values = [];
  let Currentday = new Date().getFullYear();
  // const min_year = min_date.value ? new Date(min_date.value).getFullYear() : '';
  // const max_year = max_date.value ? new Date(min_date.value).getFullYear() : '';

  for (let i = Currentday - 10; i < Currentday + 10; i++) {
    // const min_res = min_year ? i < min_year : false;
    // const max_res = max_year ? i > max_year : false;
    const disabled = false; //min_res  ||  max_res;

    year.push({ text: i.toString(), value: i, disabled });
  }
  year.defaultIndex = year.values.indexOf(Y); //设置默认选项当前年
  return year;
}

function setMonthColumn(cur_date) {
  let month = []; //获取12月数组

  month = Object.keys(Array.apply(null, { length: 12 })).map(function (item) {
    const month_num = +item + 1;
    const c_date = parseTime(new Date(cur_date).setMonth(item), '{y}-{m}-{d} {h}:{i}:{s}');
    console.log(c_date);
    const disabled = setDisabled(c_date);

    if (month_num < 10) {
      return { text: '0' + month_num, value: '0' + month_num, disabled };
    } else {
      return {
        text: month_num.toString(),
        value: month_num.toString(),
        disabled: disabled
      };
    }
  });
  return month;
}

// 获取当月天数并生成数据
function setDayColumn(Y, M, cur_date) {
  let days = getCountDays(Y, M);
  let day = []; //创建当月天数数组
  day = Object.keys(Array.apply(null, { length: days })).map(function (item) {
    const day_num = +item + 1;
    const c_date = parseTime(new Date(cur_date).setDate(day_num), '{y}-{m}-{d} {h}:{i}:{s}');
    const disabled = setDisabled(c_date);
    if (day_num < 10) {
      return { text: '0' + day_num, value: '0' + day_num, disabled };
    } else {
      return {
        text: day_num.toString(),
        value: day_num.toString(),
        disabled: disabled
      };
    }
  });
  // day.splice(0, 1);
  return day;
}

function setHourColumn(cur_date) {
  const hour = Object.keys(Array.apply(null, { length: 24 })).map(function (item) {
    const c_date = parseTime(new Date(cur_date).setHours(item), '{y}-{m}-{d} {h}:{i}:{s}');
    const disabled = setDisabled(c_date);
    // console.log(c_date, '')
    if (item < 10) {
      return { text: '0' + item, value: '0' + item, disabled };
    } else {
      return {
        text: item.toString(),
        value: item.toString(),
        disabled: disabled
      };
    }
  });
  return hour;
}

function setMinColumn(cur_date) {
  const mi = Object.keys(Array.apply(null, { length: 60 })).map(function (item) {
    const c_date = parseTime(new Date(cur_date).setMinutes(item), '{y}-{m}-{d} {h}:{i}:{s}');
    const disabled = setDisabled(c_date);
    // console.log(c_date)
    if (+item < 10) {
      return { text: '0' + item, value: '0' + item, disabled };
    } else {
      return {
        text: item.toString(),
        value: item.toString(),
        disabled: disabled
      };
    }
  });
  return mi;
}

function setSecondsColumn(cur_date) {
  const ss = Object.keys(Array.apply(null, { length: 60 })).map(function (item) {
    const c_date = parseTime(new Date(cur_date).setSeconds(item), '{y}-{m}-{d} {h}:{i}:{s}');
    const disabled = setDisabled(c_date);
    if (+item < 10) {
      return { text: '0' + item, value: '0' + item, disabled };
    } else {
      return {
        text: item.toString(),
        value: item.toString(),
        disabled
      };
    }
  });

  return ss;
}

function getCountDays(year, month) {
  //获取某年某月多少天
  let day = new Date(year, month, 0);
  return day.getDate();
}

// 关闭弹框
function confirmOn() {
  emit('changeValue');
}

//时间选择器关闭 值不改变并关闭弹框
function cancelOn({ selectedValues }) {
  confirmOn();
}

function handleConfirmDate(values) {
  const sec = props.seconds ? values[5] : '00';
  let end_val = values[0] + '-' + values[1] + '-' + values[2] + ' ' + values[3] + ':' + values[4] + ':' + sec;
  return end_val;
}

// 时间选择器确定 值改变
function onConfirm({ selectedValues }) {
  confirmOn();
  emit('confirm', handleConfirmDate(selectedValues));
}
</script>
